package com.crm.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crm.backend.domain.entity.RestBean;
import com.crm.backend.domain.po.Contact;
import com.crm.backend.service.IContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/v1/contact")
public class ContactController {

    @Autowired
    private IContactService contactService;

    /**
     * 新增客户联系人
     * @param contact 客户联系人信息
     * @return RestBean封装的响应结果
     */
    @PostMapping
    public RestBean<Void> addContact(@RequestBody Contact contact) {
        if(contact.getConName().length()>0) {
            boolean savedContact = contactService.save(contact);
            return RestBean.success();
        }else {
            return RestBean.failure(400,"请求参数异常");
        }
    }

    /**
     * 修改客户联系人
     * @param id 客户联系人编号
     * @param contact 修改后的客户联系人信息
     * @return RestBean封装的响应结果
     */
    @PutMapping("/{id}")
    public RestBean<Void>  updateContact(@PathVariable(value = "id") Integer id, @RequestBody Contact contact) {
        contact.setConId(id);
        boolean updatedContact = contactService.updateById(contact);
        if (updatedContact) {
            return RestBean.success();
        } else {
            return RestBean.failure(404, "客户联系人未找到");
        }
    }

    /**
     * 删除客户联系人
     * @param id 客户联系人编号
     * @return RestBean封装的响应结果
     */
    @DeleteMapping("/{id}")
    public RestBean<Void> deleteContact(@PathVariable(value = "id") Integer id) {
        boolean deleted = contactService.removeById(id);
        if (deleted) {
            return RestBean.success();
        } else {
            return RestBean.failure(404, "客户联系人未找到");
        }
    }

    /**
     * 查询客户联系人
     * @param cusId 客户编号
     * @param page 页码
     * @param size 每页大小
     * @return RestBean封装的响应结果
     */
    @GetMapping
    public RestBean<List<Contact>> getContacts(@RequestParam(value = "cusId") Integer cusId,
                                               @RequestParam(value = "page",defaultValue = "1") Integer page,
                                               @RequestParam(value = "size",defaultValue = "10") Integer size) {
        List<Contact> contacts = contactService.list(new QueryWrapper<Contact>().eq("cus_id", cusId));
        return RestBean.success(contacts);
    }
}
